#!/usr/bin/evn python
# -*- coding: utf-8 -*-

from pydantic import BaseModel, ValidationError, field_validator


class AddressError(ValueError):
    code = '错误类型'
    msg_template = '当前地址长度不对，它应该需要{errmsg}，当前传入的值为：{value}'

    def __init__(self, errmsg, value):
        self.errmsg = errmsg
        self.value = value
        super().__init__(self.msg_template.format(errmsg=errmsg, value=value))


# noinspection PyMethodParameters
class Person(BaseModel):
    username: str
    address: str

    @field_validator("address")
    @classmethod
    def address_rule(cls, address):
        # 如果地址长度小于6，那么则返回
        if len(address) < 6:
            raise AddressError(errmsg='小于6', value=address)
        elif len(address) > 12:
            raise AddressError(errmsg='大于12', value=address)
        return address


if __name__ == '__main__':
    try:
        user = Person(username='xiaozhong', address='1345')
    except ValidationError as e:
        print('errors', e.errors())
    else:
        print(user.username, user.address)

    # class Person(BaseModel):
    #     name: str
    #     nums: str
    #     age: Optional[int]
    #
    #
    # if __name__ == '__main__':
    #     try:
    #         user = Person(name='xiaozhong')
    #     except ValidationError as e:
    #         # print(e.errors())
    #         # print(e.json())
    #         print(str(e))
    #     else:
    #         print(user.name, user.age)
